package com.ptu.server.Impl;

import com.ptu.dto.AddressDTO;
import com.ptu.dto.AddressUpdateDTO;
import com.ptu.dto.UserDTO;
import com.ptu.entity.Address;
import com.ptu.mapper.AddressMapper;
import com.ptu.server.AddressServer;
import com.ptu.util.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressServerImpl implements AddressServer {
    @Autowired
    AddressMapper addressMapper;

    @Override
    public List<Address> list() {
        //获取用户id
        UserDTO user = UserHolder.getUser();
        System.out.println("获取地址信息"+ user.getId());
        List<Address> list = addressMapper.list(user.getId());
        return list;
    }

    @Override
    public void add(AddressDTO addressDTO) {
        UserDTO user = UserHolder.getUser();
        Integer userId = user.getId();

        Address address = new Address();
        //把DTO对象转换为实体对象，用胡图工具
        BeanUtils.copyProperties(addressDTO, address);

        address.setUserId(userId);

        List<Address> list = addressMapper.list(user.getId());

        if (list.size() > 0) {
            address.setIsDefault(0);
        } else {
            address.setIsDefault(1);
        }

        addressMapper.add(address);

    }

    @Override
    public void delete(Integer id) {
        addressMapper.delete(id);
    }

    @Override
    public void update(AddressUpdateDTO addressUpdateDTO) {
        UserDTO user = UserHolder.getUser();
        Integer userId = user.getId();

        Address address = new Address();
        BeanUtils.copyProperties(addressUpdateDTO, address);

        address.setUserId(userId);
        addressMapper.update(address);
    }

    @Transactional
    @Override
    public void setDefault(Integer id) {
        UserDTO user = UserHolder.getUser();
        Integer userId = user.getId();

        Integer oldId = addressMapper.getDefaultId(userId);
        if (oldId == null) {
            addressMapper.setDefault(id, userId);
        }else {
            //如果已经存在默认地址，则先取消默认地址，再设置新的默认地址
            addressMapper.deleteDefault(oldId, userId);
            addressMapper.setDefault(id, userId);
        }


    }

    @Override
    public Address getDefault() {
        System.out.println("获取默认地址");
        Integer userId = UserHolder.getUser().getId();

        Address defaultAddress = addressMapper.getDefault(userId);

        return defaultAddress;
    }
}
